package com.deer.wms.ware.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.system.manage.service.CodeRuleService;
import com.deer.wms.system.manage.service.ValidatorService;
import com.deer.wms.ware.task.constant.WareTaskConstant;
import com.deer.wms.ware.task.dao.OutMasterMapper;
import com.deer.wms.ware.task.model.SO.SoMaster;
import com.deer.wms.ware.task.model.SO.SoMasterCriteria;
import com.deer.wms.ware.task.model.out.OutDetail;
import com.deer.wms.ware.task.model.out.OutMaster;
import com.deer.wms.ware.task.model.out.OutMasterDto;
import com.deer.wms.ware.task.model.pickTask.PickTask;
import com.deer.wms.ware.task.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 发运单master 服务实现类
 * </p>
 *
 * @author luowei
 * @since 2022-04-18 17:42:23
 */
@Service
public class OutMasterServiceImpl extends SuperServiceImpl<OutMasterMapper, OutMaster> implements OutMasterService {
    @Autowired
    SoMasterService soMasterService;
    @Autowired
    SoDetailService soDetailService;
    @Autowired
    OutDetailService outDetailService;
    @Autowired
    ValidatorService validatorService;
    @Autowired
    InventoryService inventoryService;
    @Autowired
    InventoryTransactService inventoryTransactService;
    @Autowired
    OutMasterMapper outMasterMapper;
    @Autowired
    CodeRuleService codeRuleService;
    @Autowired
    private PickTaskService pickTaskService;

    @Override
    public List<OutMasterDto> findList(SoMasterCriteria criteria) {
        return outMasterMapper.findList(criteria);
    }

    @Override
    public String createOutBill(SoMaster soMaster, List<OutDetail> outDetails, CurrentUser currentUser) {
        //Step1.生成出库单out_master
        OutMaster outMaster = new OutMaster(soMaster);

        String billNo = codeRuleService.generateCodeByRedis("Out");
        outMaster.setBillNo(billNo);
        outMaster.setState(WareTaskConstant.SO_STATE_OUTED);
        outMaster.setCreateUserId(currentUser.getUserId());
        outMaster.setCreateUserName(currentUser.getUserName());
        this.save(outMaster);
        Set<OutDetail> outDetailSet = new HashSet<>();
        for (OutDetail outDetail : outDetails) {
            OutDetail newOutDetail = new OutDetail();
            BeanUtils.copyProperties(outDetail, newOutDetail);
            newOutDetail.setBillNo(billNo);
            outDetailSet.add(newOutDetail);
        }
//        Set<OutDetail> outDetail = outDetails.stream().map(item -> {
//            item.setBillNo(billNo);
//            return item;
//        }).collect(Collectors.toSet());
        outDetailService.saveBatch(outDetailSet);
        //Step2.生产出库单明细out_detail
        //说明：这里不专门使用out_detail作为出库明细，使用拣货任务即可
        //更新拣货任务关联的出库单id  记录时间和操作人
//        for (PickTask pickTask : pickTasks) {
//            pickTask.setOutMasterId(outMaster.getOutMasterId());
//            pickTask.setOutMasterCode(billNo);
//            pickTask.setDeliveryUserId(currentUser.getUserId());
//            pickTask.setDeliveryUserName(currentUser.getUserName());
//            pickTask.setDeliveryTime(DateUtil.now());
//        }
//
//        pickTaskService.updateBatchById(pickTasks);
        return billNo;
    }

    @Override
    public void confirmOutBill(String outBillNo, CurrentUser currentUser) {
        //查询出库单
//        OutMaster outMaster = this.getOneByField("bill_no", outBillNo);
//        List<OutDetail> outDetails = outDetailService.getListByField("bill_no", outBillNo);
//        //根据出库单生成库存事务
//        for (OutDetail outDetail : outDetails) {
//            //Step1.判断收货单是否满足确认的条件 修改状态
//            if(ObjectUtil.notEqual(WareTaskConstant.SO_DETAIL_STATE_INIT, outDetail.getState())){
//                throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR, "出库单不为新建状态，不可确认出库!");
//            }
//
//            //Step2.生成库存事务请求 并提交
//            InventoryTransact inventoryTransact = this.toStockRequest(outMaster, outDetail, currentUser);
//            inventoryTransactService.run(inventoryTransact);
//
//            outDetail.setState(WareTaskConstant.SO_DETAIL_STATE_ALL_SEND);
//
//            //Step3.1 回写上游单据[出库任务明细]状态
//            SoDetail soDetail = soDetailService.getById(outDetail.getSoDetailId());
//            soDetail.setDeliveryQuantity(soDetail.getDeliveryQuantity() + outDetail.getQuantity());
//            if (ObjectUtil.equals(soDetail.getOrderQuantity(), soDetail.getDeliveryQuantity())) {
//                soDetail.setDelivState(WareTaskConstant.SO_DETAIL_STATE_ALL_SEND);
//            } else {
//                soDetail.setDelivState(WareTaskConstant.SO_DETAIL_STATE_PART_SEND);
//            }
//            soDetailService.updateById(soDetail);
//        }
//        //Step3.2 回写上游单据[出库任务]状态
//        SoMaster soMaster = soMasterService.getById(outMaster.getSoMasterId());
//        List<SoDetail> soDetails = soDetailService.findByBillNo(soMaster.getBillNo());
//        boolean flag = true;
//        for (SoDetail soDetail : soDetails) {
//            if (ObjectUtil.notEqual(WareTaskConstant.SO_DETAIL_STATE_ALL_SEND, soDetail.getDelivState())) {
//                flag = false;
//                break;
//            }
//        }
//        if (flag) {
//            soMaster.setDelivState(WareTaskConstant.SO_STATE_ALL_OUTED);
//        } else {
//            soMaster.setDelivState(WareTaskConstant.SO_STATE_PART_OUTED);
//        }
//        soMasterService.updateById(soMaster);
//
//        //Step4.更新出库单/出库单明细状态
//        //更新明细状态
//        outDetailService.updateBatchById(outDetails);
//        //更新出库单状态
//        outMaster.setState(WareTaskConstant.SO_STATE_ALL_OUTED);
//        this.updateById(outMaster);
    }

    @Override
    public String createOutBillBySoMaster(SoMaster soMaster, CurrentUser currentUser) {
        // 增加生成出库单数据
        //Step1.生成出库单out_master
        OutMaster outMaster = new OutMaster(soMaster);
        // 出库单
        String billNo = codeRuleService.generateCode("OUT");
        outMaster.setBillNo(billNo);
        outMaster.setState(WareTaskConstant.SO_STATE_OUTED);
        outMaster.setCreateUserId(currentUser.getUserId());
        outMaster.setCreateUserName(currentUser.getUserName());
        this.save(outMaster);
        // 出库单明细
        // 查询出对应的拣货任务--每一条拣货任务对应一条出库单明细
        List<PickTask> pickTasks = pickTaskService.list(new QueryWrapper<PickTask>().eq("so_master_id", soMaster.getSoMasterId()));
        List<OutDetail> outDetailList = new ArrayList<OutDetail>();
        for(PickTask pickTask:pickTasks){
            OutDetail outDetail=new OutDetail();
            // 单号
            outDetail.setBillNo(outMaster.getBillNo());
            // 明细单号
            outDetail.setDetailNo(pickTask.getPickTaskCode());
            // 状态 2 发货
            outDetail.setState(2);
            // 物料编码
            outDetail.setItemCode(pickTask.getItemCode());
            outDetail.setItemName(pickTask.getItemName());
            outDetail.setImgUrl(pickTask.getImgUrl());
            // 包装信息
            outDetail.setPackDetailId(pickTask.getPackDetailId());
            outDetail.setPackDescribe(pickTask.getPackDescribe());
            // 订货数
            outDetail.setDeliveryQuantity(pickTask.getPickQuantity());
            // 容器
            outDetail.setBoxCode(pickTask.getBoxCode());
            // 库位编码
            outDetail.setCellCode(pickTask.getCellCode());
            // 批次号
            outDetail.setBatchName(pickTask.getBatchName());
            // 批次Id
            outDetail.setBatchId(pickTask.getBatchId());
            // 出库任务明细Id
            outDetail.setSoDetailId(pickTask.getSoDetailId());
            outDetailList.add(outDetail);
        }
        // 批量插入
        outDetailService.saveBatch(outDetailList);
        return billNo;
    }


    /**
     * 根据出库单明细生成库存事务
     * @param outDetail 出库单明细
     * @return InventoryTransact
     */
    private InventoryTransact toStockRequest(OutMaster master, OutDetail outDetail, CurrentUser currentUser) {
//        InventoryTransact inventoryTransact = new InventoryTransact();
//        //Step1.准备数据
//        //仓库
//        inventoryTransact.setWareId(master.getWareId());
//        inventoryTransact.setWareName(master.getWareName());
//        //货主
//        inventoryTransact.setToOrganizationId(master.getOrganizationId());
//        inventoryTransact.setToOrganizationName(master.getOrganizationName());
//        //库位
//        inventoryTransact.setFromCellCode(outDetail.getCellCode());
//        //容器
//        inventoryTransact.setFromBoxCode(outDetail.getBoxCode());
//        //物料
//        inventoryTransact.setItemCode(outDetail.getItemCode());
//        inventoryTransact.setItemName(outDetail.getItemName());
////        inventoryTransact.setSpec(outDetail.getSpec());
////        inventoryTransact.setModel(outDetail.getModel());
////        inventoryTransact.setImgUrl(outDetail.getImgUrl());
//        //批次
//        inventoryTransact.setFromBatchId(outDetail.getBatchId());
//        inventoryTransact.setFromBatchName(outDetail.getBatchName());
//        //数量
//        inventoryTransact.setToQuantity(outDetail.getQuantity());
//        //包装 转换率
//        inventoryTransact.setFromPackDetailId(outDetail.getPackDetailId());
//        inventoryTransact.setFromPackDescribe(outDetail.getPackDescribe());
//        inventoryTransact.setFromTransRatio(outDetail.getTransRatio());
//        //创建人 时间
//        inventoryTransact.setCreateUserId(currentUser.getUserId());
//        inventoryTransact.setCreateUserName(currentUser.getUserName());
//        inventoryTransact.setCreateTime(DateUtil.now());
//        //事务类型
//        inventoryTransact.setTransactType(InventoryConstant.INVENTORY_TYPE_OUT);
//        //来源单据号
//        inventoryTransact.setBillNo(outDetail.getDetailNo());
//
//        //Step2.保存，返回
//        inventoryTransactService.save(inventoryTransact);
//        return inventoryTransact;
        return null;
    }
}
